package com.quectel.cms.controller.parkingcard;


import com.google.common.base.Preconditions;
import com.quectel.business.common.parking.ParkingGateCmdBusiness;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.parkingcard.CorrectTimeReq;
import com.quectel.cms.vo.parkingcard.FreezeReq;
import com.quectel.constant.core.parkingcard.ParkingCardMemberConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.parkingcard.dto.ParkingCardMemberDto;
import com.quectel.core.module.parkingcard.service.ParkingCardMemberService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/04/18 17:23
 */
@RestController
@RequestMapping("parkingCardMember")
@Tag(name = "ParkingCardMemberController", description = "停车卡会员相关api")
public class ParkingCardMemberController extends BaseController {

    @DubboReference
    private ParkingCardMemberService parkingCardMemberService;
    @Autowired
    private ParkingGateCmdBusiness parkingGateCmdBusiness;

    /**
     * 导出记录
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "parkingCardMember:exportExcel")
    @Operation(summary = "导出会员")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<ParkingCardMemberDto> result = PageFetchKit.fetchAll(r -> parkingCardMemberService.queryList(r), request.getParams());
        String[] headers = new String[]{"所属小区", "车位", "车牌号码", "车牌颜色", "车主姓名", "车主手机", "冻结状态", "累计节省金额", "有效截止日", "加入会员时间"};
        List<String[]> dataList = new ArrayList<>();
        for (ParkingCardMemberDto data : result) {
            String[] item = new String[headers.length];
            item[0] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : SystemConstants.EMPTY_STR;
            item[1] = Objects.nonNull(data.getCarParkingSpace()) ? data.getCarParkingSpace().getName() : SystemConstants.EMPTY_STR;
            item[2] = data.getLicense();
            item[3] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.LICENSE_COLOR, data.getLicenseColor() + "");
            item[4] = Objects.nonNull(data.getCar()) ? data.getCar().getOwnerName() : SystemConstants.EMPTY_STR;
            item[5] = Objects.nonNull(data.getCar()) ? data.getCar().getOwnerMobile() : SystemConstants.EMPTY_STR;
            item[6] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.ParkingCardMemberFreezeStatus, data.getIsFreeze() + "");
            item[7] = data.getCumulativeSavings().toPlainString();
            item[8] = DateUtils.format(data.getDeadline(), DateUtils.FormatType.COMMON);
            item[9] = DateUtils.format(data.getJoinTime(), DateUtils.FormatType.COMMON);
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "月卡会员", headers, dataList, "月卡会员");

    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "parkingCardMember:list")
    @Operation(summary = "分页列表")
    public Response<Page<ParkingCardMemberDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = parkingCardMemberService.queryTotal(request.getParams());

        List<ParkingCardMemberDto> list = null;
        if (total > 0) {
            list = parkingCardMemberService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ParkingCardMemberDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ParkingCardMemberDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "parkingCardMember:edit")
    @Operation(summary = "查询单条记录")
    public Response<ParkingCardMemberDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (parkingCardMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingCardMemberDto parkingCardMemberDto = parkingCardMemberService.selectById(id);

        return Response.<ParkingCardMemberDto>ok().wrap(parkingCardMemberDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "parkingCardMember:info")
    @Operation(summary = "查询单条记录")
    public Response<ParkingCardMemberDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (parkingCardMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingCardMemberDto parkingCardMemberDto = parkingCardMemberService.selectById(id);

        return Response.<ParkingCardMemberDto>ok().wrap(parkingCardMemberDto);
    }

    /**
     * 根据车辆查询会员
     *
     * @param
     * @return
     */
    @GetMapping("info")
    @RequirePermissions(values = "parkingCardMember:info")
    @Operation(summary = "根据车辆查询会员")
    public Response<ParkingCardMemberDto> info(
            @Parameter(description = "小区id", required = true) @RequestParam Long villageId,
            @Parameter(description = "车牌号", required = true) @RequestParam String license,
            @Parameter(description = "车牌颜色", required = true) @RequestParam Byte licenseColor
    ) {
        ParkingCardMemberDto memberDto = parkingCardMemberService.selectOneMember(villageId, license, licenseColor);
        if (Objects.isNull(memberDto)) {
            return Response.error("会员不存在");
        }
        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(memberDto.getId()));
        if (parkingCardMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        return Response.<ParkingCardMemberDto>ok().wrap(memberDto);
    }

    /**
     * 修改会员截止日
     *
     * @param correctTimeReq
     * @return
     */
    @PostMapping("correct")
    @RequirePermissions(values = "parkingCardMember:edit")
    @Operation(summary = "修改会员截止日")
    public Response<Object> correct(@RequestBody @Validated CorrectTimeReq correctTimeReq) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(correctTimeReq.getId()));
        if (parkingCardMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingCardMemberDto parkingCardMemberDto = parkingCardMemberService.selectById(correctTimeReq.getId());
        if (ParkingCardMemberConstants.MemberIsFreezeEnum.IS_FREEZE.getFreezeStatus()
                .equals(parkingCardMemberDto.getIsFreeze())) {
            return Response.error("该月卡会员被冻结，不允许修正");
        }
        parkingCardMemberDto.setDeadline(correctTimeReq.getCorrectTime());
        parkingCardMemberService.correct(parkingCardMemberDto);

        // 重新授权
        parkingGateCmdBusiness.authorizeByMember(parkingCardMemberDto.getId());

        return Response.ok();
    }

    /**
     * 冻结会员
     *
     * @param freezeReq
     * @return
     */
    @PostMapping("freeze")
    @RequirePermissions(values = "parkingCardMember:edit")
    @Operation(summary = "冻结会员")
    public Response<Object> freeze(@RequestBody @Validated FreezeReq freezeReq) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(freezeReq.getId()));
        if (parkingCardMemberService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingCardMemberDto newlyDto = new ParkingCardMemberDto();
        newlyDto.setId(freezeReq.getId());
        newlyDto.setIsFreeze(freezeReq.getFreezeStatus());
        parkingCardMemberService.updateById(newlyDto);

        ParkingCardMemberDto memberDto = parkingCardMemberService.selectCacheById(freezeReq.getId());
        Preconditions.checkNotNull(memberDto);
        if (ParkingCardMemberConstants.MemberIsFreezeEnum.IS_FREEZE
                .getFreezeStatus().equals(freezeReq.getFreezeStatus())) {
            // 冻结，撤销权限
            parkingGateCmdBusiness.revoke(memberDto.getVillageId(), memberDto.getLicense(), memberDto.getLicenseColor());
        } else if (ParkingCardMemberConstants.MemberIsFreezeEnum.NO_FREEZE
                .getFreezeStatus().equals(freezeReq.getFreezeStatus())) {
            // 解冻，重新授权
            parkingGateCmdBusiness.authorizeByMember(memberDto.getId());
        }
        return Response.ok();
    }

    /**
     * 授权设备
     *
     * @param id
     * @return
     */
    @PostMapping("auth")
    @RequirePermissions(values = "parkingCardMember:edit")
    @Operation(summary = "授权设备")
    public Response<Object> auth(@RequestBody Long id) {
        ParkingCardMemberDto memberDto = parkingCardMemberService
                .selectCacheById(id);
        if (Objects.isNull(memberDto)) {
            return Response.error("会员不存在");
        }
        if (ParkingCardMemberConstants.MemberIsFreezeEnum.IS_FREEZE
                .getFreezeStatus().equals(memberDto.getIsFreeze())) {
            return Response.error("会员被冻结");
        }

        parkingGateCmdBusiness.authorizeByMember(memberDto.getId());
        return Response.ok();
    }

    /**
     * 取消授权
     *
     * @param id
     * @return
     */
    @PostMapping("revoke")
    @RequirePermissions(values = "parkingCardMember:edit")
    @Operation(summary = "取消授权")
    public Response<Object> revoke(@RequestBody Long id) {
        ParkingCardMemberDto memberDto = parkingCardMemberService
                .selectCacheById(id);
        if (Objects.isNull(memberDto)) {
            return Response.error("会员不存在");
        }
        parkingGateCmdBusiness.revoke(memberDto.getVillageId(), memberDto.getLicense(), memberDto.getLicenseColor());
        return Response.ok();
    }

}
